package com.liuqing.www.文件解析;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.core.io.Resource;

public class Txt文件解析 {
	/**香草==<a href="path/struts2/drugsuse!commonUse.action?sessionid={0}&amp;local={5}&amp;commend={6}&amp;pcupage={4}&amp;id={2}&amp;act={3}&amp;sq={1}">
	 * String params[]={sessionid,String.valueOf(user.sq),String.valueOf(drugsInfo.getGoodsInfo().getId()),act,cupage.toString(),"drugsuse"};
			String str=useUrl.getUrl(drugsInfo.getGoodsInfo().getGoodsName(),path);
			if(str!=null && !"".equals(str)){
			String link=MessageFormat.format(str, params);
	 */
	private Map<String,String> prop;//property文件关键有类个hashmap来装数据

	private File configFile;

	private long lastModifyTime = 0L;

	private Resource resource;
	
	public void setResource(Resource resource) {
		this.resource = resource;
	}

	private void init() {
		try {
			configFile = resource.getFile();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		prop = new HashMap<String,String>();
		load();
	}

	private void load() {
		try {
			InputStreamReader read = new InputStreamReader (new FileInputStream(configFile),"UTF-8");
			BufferedReader bfr = new BufferedReader(read);
//			FileInputStream filein = new FileInputStream(configFile);
			String   s;  
            while((s=bfr.readLine())!=null){
            	String[] line = s.split("=");
            	if(line.length < 2){
            		prop.put(line[0], null);
            		continue ;
            	}
            	prop.put(line[0], line[1]);
            }  
            bfr.close(); 
			lastModifyTime = configFile.lastModified();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public Map<String,String> getContent(){
		if ((configFile == null) || (prop == null)) {
			init();
		}
		return prop;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.moloon.sonny.app.Configurable#getConfig(java.lang.String)
	 */
	public String getConfig(String key) {
		if ((configFile == null) || (prop == null)) {
			init();
		}
		if (configFile.lastModified() > lastModifyTime) {
				System.err.print("reload config file for lasttime="
						+ lastModifyTime + " and new time="
						+ configFile.lastModified());
			load();
		}

		return prop.get(key);

	}
	public String toString(){
		StringBuffer sb = new StringBuffer();
		Iterator<String> iter = prop.keySet().iterator();
		while(iter.hasNext())
		{
			String key = iter.next();
			String value = prop.get(key);
			sb.append("{"+key+"="+value+"}");
		}
		return sb.toString();
	}
}
